import { FC, MutableRefObject, useEffect } from 'react';
import FieldItem, { FieldItemProps } from './FieldItem';
import { IFormLayoutProps } from '@formily/antd/esm/form-layout';
import { Form } from 'antd';
import styles from './index.less';

interface FieldFormProps {
  formItemsRef: MutableRefObject<any>;
  layout?: IFormLayoutProps['layout'];
  fields?: FieldItemProps[];
  initialValues?: any;
}

const FieldForm: FC<FieldFormProps> = (props) => {
  const { fields, initialValues, formItemsRef } = props;
  const [form] = Form.useForm();

  useEffect(() => {
    form.setFieldsValue(initialValues);
  }, [initialValues]);

  return (
    <Form
      form={form}
      initialValues={initialValues}
      colon={false}
      labelCol={{ span: 8 }}
      labelAlign="left"
      onValuesChange={(_, allValues) => {
        formItemsRef.current.formItems = allValues;
      }}
      className={styles['tree-form']}
    >
      {fields?.map((field) => (
        <FieldItem key={field.name} {...field} values={initialValues} />
      ))}
    </Form>
  );
};

export default FieldForm;
